package com.lmz.product.exception;

import com.lmz.common.exception.BizCodeEnume;
import com.lmz.common.utils.R;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 处理所有异常
 */
//@ResponseBody
//@ControllerAdvice(basePackages = "com.lmz.product.controller")
@RestControllerAdvice(basePackages = "com.lmz.product.controller")
public class GulimallException {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        Map<String, String> errMap = new HashMap<>();
        result.getFieldErrors().forEach((item) -> {
            errMap.put(item.getField(), item.getDefaultMessage());
        });
        return R.error(BizCodeEnume.VALID_EXCEPTION.getCode(), BizCodeEnume.VALID_EXCEPTION.getMsg()).put("data", errMap);
    }

    //@ExceptionHandler(value = Throwable.class)
    //public R ahndleException(Throwable e) {
    //    return R.error(BizCodeEnume.UNKNOWN_EXCEPTION.getCode(), BizCodeEnume.UNKNOWN_EXCEPTION.getMsg());
    //}
}